/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.merak.core.model;

import java.io.Serializable;

import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;

import org.merak.core.text.json.Jsonfiable;
import org.merak.core.text.json.ObjectJson;

/**
 * This class is supposed to be extended by all identifiable objects.
 * Basically, it holds only a single attribute: the id, which has the properties
 * of being comparable and theoretically unique inside a scope.
 * This class alone cannot ensure the scope uniqueness, but it forbids Id update operations.
 * Even so, there is a setId(T id) method that can be called only once,
 * otherwise it will throw a runtime IdentifierException. Of course, this exception
 * will be thrown also if id has already been set by constructor.
 *
 * @author fmarinho
 **/
@MappedSuperclass
public abstract class Identified<T extends Serializable & Comparable<T>>
           implements Identifiable<T>,Jsonfiable
{

	//~ Attributes ////////////////////////////////////////////////////////////////
	//*****************************************************************************
	/** The identifier: a symbol that establishes the identity of the one bearing it */
	private T id;

	//~ Constructors //////////////////////////////////////////////////////////////
	//*****************************************************************************
	/** Obliges to initialize the Id, even if it is null. It can be called only
	 * by subclasses, to reinforce the abstract nature of this class */
	protected Identified(T id) {

		this.setId(id);

	}

	//~ Methods ///////////////////////////////////////////////////////////////////
	//*****************************************************************************
	public void setId(T id) {

		/* Id update is illegal... An update occurs when this.id:
		 * 1. is already set
		 * 2. AND is different of parameter id */
		if ( this.id!=null && !this.id.equals(id) ) {
			throw new IdentifierException(
				"ID update is an illegal operation: One object of ["
				+ this.getClass().getName()
				+ "] is already identified by ID "
				+ this.id
			);
		}

		// Set id since all goes right
		this.id = id;

	}
	//*****************************************************************************
	@Override
	@Id @GeneratedValue(generator="ID")
	public T getId() {
		return this.id;
	}
	//*****************************************************************************
	@SuppressWarnings("unchecked")
	@Override
	@Transient
	public Class<T> getIdentifierClass() {

		// The case when object has not been identified yet
		if (this.getId() == null) {
			throw new IdentifierException(
				"Impossible to know Id Class since it has not been identified yet: id == null."
			);
		}
		return (Class<T>) this.getId().getClass();

	}
	//*****************************************************************************
	@Override
	public boolean hasId(T value) {

		// The case when object has not been identified yet
		if (this.getId() == null) {
			return value==null;
		}

		// The case when object has already been identified
		return this.getId().equals(value);

	}
	//*****************************************************************************
	@Override
	public boolean selfsame(Identifiable<T> object) {

		// The case when object has not been identified yet
		if (this.getId() == null) throw new IdentifierException(
			"This object cannot be compared since it has not been " +
			"identified yet: id == null."
		);

		// The case when object has already been identified
		return this.getClass().isInstance(object) && this.getId().equals(object.getId());

	}
	//*****************************************************************************
	@Override
	public int hashCode() {

		// The case when object has not been identified yet
		if (this.getId() == null) return 0;

		// The case when object has already been identified
		return this.getId().hashCode();

	}
	//*****************************************************************************
	@Override
	@SuppressWarnings("unchecked")
	public boolean equals(Object object) {

		// Null objects are not equal to instanced objects
		if (object == null) return false;

		try {
			return  object != null &&
					this.hasId( ((Identifiable<T>) object).getId() );
		}
		catch (Throwable t) {
			return false;
		}

	}
	//*****************************************************************************
	@Override
	public String toString() {
		return this.getClass().getSimpleName() + "#" + this.getId();
	}
	//*****************************************************************************
	@Override
	public String toJson() {
		return ObjectJson.toJson(this);
	}
	//*****************************************************************************

}